package cn.chencq.gdt.utils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ThreadPoolUtil {

	private static Logger logger = LoggerFactory
			.getLogger(ThreadPoolExecutor.class);

	private static ExecutorService threadPool = new ThreadPoolExecutor(10, 10,
			5 * 1000, TimeUnit.MINUTES, new LinkedBlockingDeque<Runnable>(),
			new ThreadCreateFactory());

	static class ThreadCreateFactory implements
			java.util.concurrent.ThreadFactory {

		final ThreadGroup group;
		final AtomicInteger threadNumber = new AtomicInteger(1);
		final String namePrefix;

		public ThreadCreateFactory() {
			SecurityManager s = System.getSecurityManager();
			group = (s != null) ? s.getThreadGroup() : Thread.currentThread()
					.getThreadGroup();
			namePrefix = "pool-thread-";
		}

		@Override
		public Thread newThread(Runnable r) {
			Thread t = new Thread(group, r, namePrefix
					+ threadNumber.getAndIncrement(), 0);
			if (t.isDaemon())
				t.setDaemon(false);
			if (t.getPriority() != Thread.NORM_PRIORITY)
				t.setPriority(Thread.NORM_PRIORITY);
			return t;
		}

	}

	/**
	 * 通过线程池执行子任务，该任务可能失败，但是不返回错误信息，需要通过日志
	 * 
	 * @param task
	 *            待执行的子任务
	 */
	public static void execute(Runnable task) {
		try {
			threadPool.execute(task);
		} catch (Exception e) {
			logger.error("提交子任务失败", e);
		}
	}

	/**
	 * 通过线程池执行带结果返回的子任务，如果子任务提交失败返回null
	 * 
	 * @param task
	 *            子任务
	 * @return 子任务执行的{@link Future}.如果提交子任务失败返回null
	 */
	public static <T> Future<T> submit(Callable<T> task) {
		try {
			return threadPool.submit(task);
		} catch (Exception e) {
			logger.error("提交子任务失败", e);
		}
		return null;
	}

}
